package uit.edu.vn.Activity;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;

import java.util.Enumeration;

import uit.edu.vn.Utility.WebService;


import uit.edu.vn.Model.UserObject;
import uit.edu.vn.Utility.CheckInternet;
import uit.edu.vn.Utility.MyActivity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class InfoActivity extends MyActivity{
    private String userid = "";
    private String username = "";
    private String password = "";
    private static final String STRING_NAME_USERSETTING = "USER REFERENCES";
    private SharedPreferences ShareRef = null;
    private String ipLocal ;

	private UserObject userInfo;
    private ProgressDialog infoDialog;
    private Context context;
    private TextView txt_accountInfo;
    private TextView txt_ipAddress;
    private TextView txt_Capaticity;
    private TextView txt_Status;
    private TextView txt_dayRegistry;
    private TextView txt_FileUpload;
    private TextView txt_SmsUpload;
    private TextView txt_ContactUpload;

	private String results = "";
	private String passOld;
	private String passNew;
	private String passNewConfirm;
	private int flag ;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
        username = getSetting("username");
        password = getSetting("password");
        userid   = getSetting("userid");
		
		context=getBaseContext();
	      //kiem tra neu username va password rong thi ket thuc activity hien tai va goi activity login
	      if(username.equals("") && password.equals("")){
	          Intent intent = new Intent(InfoActivity.this, LoginActivity.class);
	          startActivity(intent);
	          this.finish();            	
	      }		
	  
	    
	      Log.d("flag",String.valueOf(flag));
	      System.out.println("InfoActivity");
	      System.out.println("username: "+ username);
	      System.out.println("password: "+ password);
	      System.out.println("userid:   "+ userid);
	      System.out.println("MainActivity.address.toString() : " + MainActivity.address.toString());
	      
		setContentView(R.layout.information);
		txt_accountInfo=(TextView)findViewById(R.id.txt_acountInfo);
		txt_Capaticity=(TextView)findViewById(R.id.txt_capacity);
		txt_ipAddress=(TextView)findViewById(R.id.txt_ipAddress);
		txt_dayRegistry=(TextView)findViewById(R.id.txt_dayRegistry);
		txt_FileUpload=(TextView)findViewById(R.id.txt_contactFileUpload);
		txt_Status=(TextView)findViewById(R.id.txt_Status);
		txt_SmsUpload=(TextView)findViewById(R.id.txt_smsFileUpload);
		txt_ContactUpload=(TextView)findViewById(R.id.txt_otherFileUpload);
	
		infoDialog= new ProgressDialog(this);
		infoDialog.setMessage(getResources().getString(R.string.dialog_message_progress_server));
		infoDialog.setCancelable(false);
		infoDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		// lay thong tin
		userInfo = new UserObject();
		CheckInternet chkI= new CheckInternet(context);
	    if(chkI.checkStatus().equals(true))
			{
	    		new BackGroundTask().execute();
			}
	        else
	        {
	        	Log.d("ketnoi", "ko co ket noi internet");
	        	showToast("Khong co ket noi internet");
	        
	        }
			Log.d("tag", String.valueOf(userid));

	}	
	public String getSetting(String key) {
        ShareRef = getSharedPreferences(STRING_NAME_USERSETTING, Context.MODE_WORLD_WRITEABLE);
        return ShareRef.getString(key, "");
	} 	
	//-----------cac ham xu ly khac -----------------------
	public void getInfoAll()
	{
		try {//ngay dang ky
			txt_dayRegistry.setText(userInfo.getDayRegistry());
			//ten tai khoan
			txt_accountInfo.setText(username);
			//lay dia chỉ iplocal
			ipLocal=getLocalIpAddress();
			txt_ipAddress.setText(ipLocal);
			//íp Server 
	//		txt_ipServer.setText(LoginActivity.getIPAddress().toString());
			String str=getFileSize(userInfo.getSumCapacity().toString().trim());
			txt_Capaticity.setText(str+"MB"+"/"+"50MB");
			//so luong file
			txt_FileUpload.setText(userInfo.getNumOther().toString()+"Tập tin");
			txt_ContactUpload.setText(userInfo.getNumContact().toString()+"Danh bạ");
			txt_SmsUpload.setText( userInfo.getNumSMS().toString()+"Tin nhắn ");
			CheckInternet chkI= new CheckInternet(context);
			txt_Status.setText("Đang có internet");

			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	public String getLocalIpAddress() {
		try {
		    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
		        NetworkInterface intf = en.nextElement();
		        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
		            InetAddress inetAddress = enumIpAddr.nextElement();
		            if (!inetAddress.isLoopbackAddress()) {
		                return inetAddress.getHostAddress().toString();
		            }
		        }
		    }
		} catch (SocketException ex)
		{
		 System.out.print(ex);
		}
		return null;
		}
	//
	private class BackGroundTask extends AsyncTask<Void, Void, Void>
	{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			infoDialog.show();
		}
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try {
				userInfo = WebService.getAllInfor(Integer.parseInt(userid));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			infoDialog.dismiss();
			getInfoAll();
		}
	}
//--------------------------thanh menu change password-----------------------------------
	public boolean onCreateOptionsMenu(Menu menu) 
  	 {
  	    	// TODO Auto-generated method stub
  	    	//return super.onCreateOptionsMenu(menu);
  	    	new MenuInflater(getApplicationContext()).inflate(R.menu.info_change_password, menu);
  		    return super.onCreateOptionsMenu(menu);
  	 }
  	 @Override
  	 public boolean onOptionsItemSelected(MenuItem item) 
  	 {
  		 // TODO Auto-generated method stub
  		 switch(item.getItemId())
	    {
	    	case R.id.menu_ChangePassword:{
	    		final Dialog dialog=new Dialog(InfoActivity.this);
 	    		dialog.setContentView(uit.edu.vn.Activity.R.layout.dialog);
 	    		dialog.setTitle("Đổi mật khẩu tài khoản");

 	    		Button btn_OK = (Button)dialog.findViewById(R.id.btn_ok);
 	    		Button btn_Cancel= (Button)dialog.findViewById(uit.edu.vn.Activity.R.id.btn_cancel);
 	    		btn_OK.setOnClickListener(new  View.OnClickListener() {
					
					public void onClick(View v) {
						// TODO Auto-generated method stub
						final EditText edt_passOld= (EditText)dialog.findViewById(R.id.edt_passOld);
			
						final EditText edt_passNew= (EditText)dialog.findViewById(R.id.edt_passNew);
		
						final EditText edt_passNewConfirm= (EditText)dialog.findViewById(R.id.edt_passNewConfirm);
					
					
						passOld = edt_passOld.getText().toString().trim();
						passNew = edt_passNew.getText().toString().trim();
						passNewConfirm = edt_passNewConfirm.getText().toString().trim();
						if(passOld.equals("") ||passNew.equals("") || passNewConfirm.equals("") )						
							showToast("Vui lòng điền đầy đủ thông tin!");						
						else if(passOld.equals(passNew))						
							showToast("Mật khẩu mới không được trùng mật khẩu cũ");						
						else if(!passNew.equals(passNewConfirm))						
							showToast("Mật khẩu không khớp");				
						else if(!password.equals(passOld))
							showToast("Sai mật khẩu cũ");						
						else{			
							try {			
								System.out.println("passOld: "+passOld);
								System.out.println("passNew: "+passNew);
								new AsyncTask<Void, Void, Void>()
								{
									@Override
									protected void onPreExecute() {
										// TODO Auto-generated method stub
										infoDialog.show();
										super.onPreExecute();
									}
									@Override
									protected Void doInBackground(Void... params) 
									{
										// TODO Auto-generated method stub
										try {
											results = WebService.ChangePassword(Integer.parseInt(userid), passNew);
										} catch (NumberFormatException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										} catch (Exception e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
										return null;
									}
									@Override
									protected void onPostExecute(Void result) 
									{
										// TODO Auto-generated method stub
										super.onPostExecute(result);
										infoDialog.dismiss();
										if(results.equals("0")){
											showToast("Đổi mật khẩu thất bại");
										}else{
											showToast("Đổi mật khẩu thành công");
											saveSetting("password", passNew);
											password = passNew;
											dialog.dismiss();
										}
									}
								}.execute();

							} catch (NumberFormatException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

						Log.d("tag",passOld);		
						
					}
				});
 	    		btn_Cancel.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
 	    		dialog.show();			    		
	    		return true;
	    	}	
	    	
	    	//dang xuat
  		 
	    }
  		return false;
  	}
  	 
 	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	// TODO Auto-generated method stub
    	if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0)
    	{
    		showConfirmDialog(getResources().getString(R.string.dialog_thongbao),getResources().getString(R.string.dialog_message_thoat) , new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					logOut();
					finish();
				}
			});
    	}
    	return super.onKeyDown(keyCode, event);
    }
   
}
